package com.zrb.mobile.ucenter;

import java.util.ArrayList;
import java.util.Date;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.hhpm.lib.pullrefresh.PullRefreshLayout;
import com.hhpm.lib.swipelistview.SwipeMenu;
import com.hhpm.lib.swipelistview.SwipeMenuCreator;
import com.hhpm.lib.swipelistview.SwipeMenuItem;
import com.hhpm.lib.swipelistview.SwipeMenuListView.OnMenuItemClickListener;
import com.hhpm.lib.swipelistview.SwipeMenuListView.OnSwipeListener;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.DiscoverDetailOneActivity;
import com.zrb.mobile.MoneyDetailActivity;
import com.zrb.mobile.ProjectDetailActivity;
import com.zrb.mobile.R;
import com.zrb.mobile.adapter.AttentionFindAdapter;
import com.zrb.mobile.adapter.model.AttentionFindDtos;
import com.zrb.mobile.ui.SwipeMenuListViewEx;
import com.zrb.mobile.ui.onLoadMoreListener;
import com.zrb.mobile.utility.CollectionHelper;
import com.zrb.mobile.utility.CollectionHelper.onCollectionListener;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.ZrbRestClient;
import com.zrb.mobile.utility.ZrbRestClient.HttpResponseListener;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import com.zrb.mobile.adapter.model.AttentionFindDto;

public class Collection_ChoicenessFragment extends Fragment implements
		onLoadMoreListener, onCollectionListener {

	SwipeMenuListViewEx mListView;
	AttentionFindAdapter mFindAdapter;
	Handler myhandler = new Handler();
	CollectionHelper mCollectionHelper;
	int currentPage = 1;
	boolean isFirstIn = true;
	int AttentionType = -1;
	public boolean isRemove;
	public AttentionFindDto aDto;
	ZrbRestClient mZrbRestClient;
	 PullRefreshLayout layout;
	boolean isReflesh=false;
	
	public static Collection_ChoicenessFragment getNewFrament(int type) {

		Collection_ChoicenessFragment tmp = new Collection_ChoicenessFragment();
		tmp.AttentionType = type;
		return tmp;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		registerBoradcastReceiver1();
		registerBoradcastReceiver2();
		registerBoradcastReceiver3();

		View view = inflater.inflate(R.layout.common_swipemenulistview,
				container, false);

		mListView = (SwipeMenuListViewEx) view.findViewById(R.id.listView);
		// mFindAdapter = new AttentionFindAdapter(this.getActivity(),new
		// ArrayList<tmpTextDto>());

		mFindAdapter = new AttentionFindAdapter(this.getActivity(),new ArrayList<AttentionFindDto>());
		mFindAdapter.setCurAttionType(AttentionType);
		mListView.initAdapter(mFindAdapter);
		mListView.setOnLoadMoreListener(this);
		initlistview();
		
	   layout = (PullRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
	    layout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
	            @Override
	            public void onRefresh() {
	            	
	            	myhandler.postDelayed(new Runnable() {
	    				@Override
	    				public void run() {
	    					currentPage=1;
	    					isReflesh=true;
	    					LoadData(-1, true);
	    				}
	    			}, 1000);
	               /* layout.postDelayed(new Runnable() {
	                    @Override
	                    public void run() {
	                        layout.setRefreshing(false);
	                    }
	                }, 5000);*/
	            }
	        });
		return view;
	}

	private void delAttention(long curId) {
		if (mCollectionHelper == null) {
			mCollectionHelper = new CollectionHelper(this.getActivity(),
					AttentionType);
			mCollectionHelper.setOnCollectionListener(this);
		}
		mCollectionHelper.onClickCollect(curId, false);
	}

	@Override
	public void onCollectionEvent() {
		// TODO Auto-generated method stub

	}

	private void initlistview() {
		// step 1. create a MenuCreator
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "open" item
				// create "delete" item
				SwipeMenuItem deleteItem = new SwipeMenuItem(
						Collection_ChoicenessFragment.this.getActivity()
								.getApplicationContext());
				// set item background
				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
						0x3F, 0x25)));
				// set item width
				deleteItem.setWidth(CommonUtil.dp2px(
						Collection_ChoicenessFragment.this.getActivity(), 90));
				// set a icon
				//deleteItem.setIcon(R.drawable.ic_delete);
				deleteItem.setTitle("取消关注");
				deleteItem.setTitleSize(15);
			//	deleteItem.setTitleSize(CommonUtil.dp2sp(getActivity(), 8));
				deleteItem.setTitleColor(Color.parseColor("#ffffff"));
				// add to menu
				menu.addMenuItem(deleteItem);
			}
		};
		// set creator
		mListView.setMenuCreator(creator);

		// step 2. listener item click event
		mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(final int position, SwipeMenu menu,
					int index) {
				// ApplicationInfo item = mAppList.get(position);
				// CommonUtil.showToast(position+"", getActivity());
				myhandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						long curId = mFindAdapter.getAt(position).id;
						mFindAdapter.removeAt(position);
						mFindAdapter.notifyDataSetChanged();
						delAttention(curId);
					}
				}, 10);
				return true;
			}
		});

		// test item long click
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				AttentionFindDto tmpDto = mFindAdapter.getAt(position);
				Intent intent;
				switch (AttentionType) {
				case Constants.FocusIntent:
					intent = new Intent(getActivity(),
							DiscoverDetailOneActivity.class);
					intent.putExtra("attention", 1);
					intent.putExtra("id", tmpDto.id);
					intent.putExtra("attentionTimes", tmpDto.collectNum);
					intent.putExtra("messageAmount", tmpDto.messageNum);
					intent.putExtra("title", tmpDto.title);
					intent.putExtra("position", position);
					intent.putExtra("from", "3");
					aDto = tmpDto;
					break;
				case Constants.FocusProject:
					intent = new Intent(getActivity(),
							ProjectDetailActivity.class);
					intent.putExtra("id", tmpDto.id);
					intent.putExtra("title", tmpDto.title);
					intent.putExtra("position", position);
					intent.putExtra("from", "4");
					aDto = tmpDto;
					break;
				default:
					intent = new Intent(getActivity(),
							MoneyDetailActivity.class);
					intent.putExtra("id", tmpDto.id);
					intent.putExtra("title", tmpDto.title);
					intent.putExtra("position", position);
					intent.putExtra("from", "4");
					aDto = tmpDto;
					break;
				}
				Collection_ChoicenessFragment.this.startActivity(intent);
			}
		});

	}

	private void hideloading() {
		User_my_collection tmpFrag = (User_my_collection) this.getActivity();
		if (tmpFrag != null)
			tmpFrag.hideloading();

	}

	private void showloading() {
		User_my_collection tmpFrag = (User_my_collection) this.getActivity();
		if (tmpFrag != null)
			tmpFrag.showloading();

	}

	@Override
	public void onResume() {
		super.onResume();
		if (this.getUserVisibleHint())
			firstLoad();
	}

	private void firstLoad() {
		if (isFirstIn) {
			isFirstIn = false;
			showloading();
			myhandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					LoadData(-1, true);
				}
			}, 1000);
		}
	}

	@Override
	public void OnLoadMoreEvent() {
		// TODO Auto-generated method stub
		currentPage++;
		myhandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				LoadData(mFindAdapter.getMinTime(), false);
			}
		}, 200);
	}

	// userStatisticDetail/getCollectIntentions?limit=10&createTime=2015-10-23%2023:59:59&zrb_front_ut=8b9737d9ea6b95316a8a3e4b6591b684
	private void LoadData(long maxtime, final boolean isreflesh) {

		String ActionType = "";
		switch (AttentionType) {
		case Constants.FocusIntent:
			ActionType = "getCollectIntentions";
			break;
		case Constants.FocusProject:
			ActionType = "getCollectProjects";
			break;
		default:
			ActionType = "getCollectFunds";
			break;
		}

		String url = String.format("userStatisticDetail/%1$s?limit=%2$s",ActionType, 10);
		if (maxtime != -1)
			url += "&createTime=" + maxtime;

		CommonUtil.InfoLog("userStatisticDetail", url);
        if(null==mZrbRestClient){
        	mZrbRestClient=new ZrbRestClient(Collection_ChoicenessFragment.this.getActivity());
        	mZrbRestClient.setOnhttpResponseListener(new HttpResponseListener() {
    			@Override
    			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {

    				CommonUtil.showToast(arg0, Collection_ChoicenessFragment.this.getActivity());
    				if (currentPage > 1)
    					mListView.hideloading();
    				else {
    					if(isReflesh) {
    						layout.setRefreshing(false);
    						mListView.setCanloadMore();
    					}
    					else hideloading();
    				}
    			}

    			@Override
    			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
    				// loadingview.Hide();
    				String results = new String(arg2);
    				if (currentPage > 1)	hideloading();
    				else {
    					if(isReflesh) {
    						layout.setRefreshing(false);
    						mListView.setCanloadMore();
    					}
    					else hideloading();
    				}
    				try {
    					Gson gson = new Gson();
    					AttentionFindDtos tmpDto = gson.fromJson(results, AttentionFindDtos.class);
    					if (tmpDto.res == 1) {
    						if (currentPage == 1) {
    							mFindAdapter.setAll(tmpDto.data);
    						} else {
    							mListView.hideloading();
    							mListView.checkloadMore(CommonUtil.getSize(tmpDto.data));
    							mFindAdapter.addAll(tmpDto.data);
    						}
    						mFindAdapter.notifyDataSetChanged();
    					} else
    						CommonUtil.showToast(tmpDto.msg, getActivity());
    				} catch (Exception e) {
    					CommonUtil.showToast(R.string.error_serverdata_loadfail,Collection_ChoicenessFragment.this.getActivity());
    				}
    			}
    		});
        	
        }
		mZrbRestClient.sessionGet(url);
	}

	public void registerBoradcastReceiver1() {

		if (Constants.FocusIntent != AttentionType)
			return;
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(Constants.FocusNum_ATTENTION_mainlist);
		// 注册广播
		Collection_ChoicenessFragment.this.getActivity().registerReceiver(
				mBroadcastReceiver1, myIntentFilter);
	}

	private BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Constants.FocusNum_ATTENTION_mainlist)) {
				CommonUtil.InfoLog("FocusNum_ATTENTION_mainlist",
						"FocusNum_ATTENTION_mainlist");
				switch (AttentionType) {
				case Constants.FocusIntent:
					String from = intent.getStringExtra("from");
					int position = intent.getIntExtra("position", -1);
					if ("2".equals(from)) {
						addCount(position);
					}
					if ("1".equals(from)) {
						int attention = intent.getIntExtra("attention", -1);
						if (attention != -1) {
							if (attention == 0) {
								// 取消关注
								CanFocus(position);
							} else {
								// 添加关注
								AddFocus(position);
							}
						}

					}

					break;

				default:
					break;
				}
			}
		}
	};

	public void registerBoradcastReceiver2() {

		if (Constants.FocusProject != AttentionType)
			return;
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(Constants.PRONum_ATTENTION_mainlist);
		// 注册广播
		Collection_ChoicenessFragment.this.getActivity().registerReceiver(
				mBroadcastReceiver2, myIntentFilter);
	}

	private BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Constants.PRONum_ATTENTION_mainlist)) {
				CommonUtil.InfoLog("PRONum_ATTENTION_mainlist",
						"PRONum_ATTENTION_mainlist");
				switch (AttentionType) {
				case Constants.FocusProject:

					int position = intent.getIntExtra("position", -1);

					int attention = intent.getIntExtra("attention", -1);
					if (attention != -1) {
						if (attention == 0) {
							// 取消关注
							CanFocus(position);
						} else {
							// 添加关注
							AddFocus(position);
						}
					}

					break;

				default:
					break;
				}
			}
		}
	};

	public void registerBoradcastReceiver3() {

		if (Constants.FocusMoney != AttentionType)
			return;
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(Constants.MONNum_ATTENTION_mainlist);
		// 注册广播
		Collection_ChoicenessFragment.this.getActivity().registerReceiver(
				mBroadcastReceiver3, myIntentFilter);
	}

	private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Constants.MONNum_ATTENTION_mainlist)) {
				CommonUtil.InfoLog("MONNum_ATTENTION_mainlist",
						"MONNum_ATTENTION_mainlist");
				switch (AttentionType) {
				case Constants.FocusMoney:

					int position = intent.getIntExtra("position", -1);

					int attention = intent.getIntExtra("attention", -1);
					if (attention != -1) {
						if (attention == 0) {
							// 取消关注
							CanFocus(position);
						} else {
							// 添加关注
							AddFocus(position);
						}
					}

					break;

				default:
					break;
				}
			}
		}
	};

	// 留言数添加
	protected void addCount(int position) {
		// int position = data.getIntExtra("position", -1);
		// TODO Auto-generated method stub
		mFindAdapter.CurrentDatas.get(position).messageNum = mFindAdapter.CurrentDatas
				.get(position).messageNum + 1;
		mFindAdapter.notifyDataSetChanged();
	}

	// 取消关注效果
	protected void CanFocus(int position) {
		mFindAdapter.CurrentDatas.remove(position);
		mFindAdapter.notifyDataSetChanged();
	}

	// 添加关注效果
	protected void AddFocus(int position) {
		mFindAdapter.CurrentDatas.add(position, aDto);
		Log.i("mFindAdapter.CurrentDatas", mFindAdapter.CurrentDatas.size()
				+ "");
		mFindAdapter.setCurrentDatas(mFindAdapter.CurrentDatas);
		mFindAdapter.notifyDataSetChanged();
	}

	/*
	 * 
	 * 
	 * 广播接收者的注册和接收
	 */
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// 销毁广播
		if (Constants.FocusIntent == AttentionType
				&& mBroadcastReceiver1 != null)
			Collection_ChoicenessFragment.this.getActivity().unregisterReceiver(
					mBroadcastReceiver1);
		if (Constants.FocusProject == AttentionType
				&& mBroadcastReceiver2 != null)
			Collection_ChoicenessFragment.this.getActivity().unregisterReceiver(
					mBroadcastReceiver2);
		if (Constants.FocusMoney == AttentionType
				&& mBroadcastReceiver3 != null)
			Collection_ChoicenessFragment.this.getActivity().unregisterReceiver(
					mBroadcastReceiver3);

	}

}
